package com.cmc6.common.util.redis;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.cmc6.common.util.ApiResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 备注：请使用注入的方式使用本工具类，不要 new，或者直接使用 {@link com.cmc6.common.util.RedisUtil}
 */
@Component
public class RedisUtilBase {

    @Value("${spring.redis.password:}")
    private String redisPassword;
    @Resource
    RedisConnectionFactory redisConnectionFactory;
    // 以 s结尾的，都是用逗号隔开的，所以这里在配置文件中，也是用逗号隔开的
    @Value("#{'${spring.redis.cluster.nodes:}'.split(',')}")
    private Set<String> nodeSet;

    private static MyRedisTemplate[] redisTemplateArr = new MyRedisTemplate[16];

    /**
     * 获取 MyRedisTemplate
     */
    @Deprecated // 原因：因为集群模式，不支持切换 db，只有 db0
    public synchronized <T> MyRedisTemplate<T> createRedisConnectionFactory(int db) {
        if (db < 0 || db > 15) {
            ApiResult.error("db 数值非法");
        }
        if (null != redisTemplateArr[db]) {
            return redisTemplateArr[db];
        }

        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        List<RedisNode> nodeList = new ArrayList<>();
        for (String item : nodeSet) {
            List<String> split = StrUtil.split(item, ':');
            nodeList.add(new RedisNode(split.get(0), Convert.toInt(split.get(1))));
        }
        redisClusterConfiguration.setClusterNodes(nodeList);
        redisClusterConfiguration.setPassword(redisPassword);
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisClusterConfiguration);
        BeanUtil.copyProperties(redisConnectionFactory, lettuceConnectionFactory);
        lettuceConnectionFactory.setDatabase(db);
        lettuceConnectionFactory.afterPropertiesSet();
        lettuceConnectionFactory.resetConnection();

        MyRedisTemplate<T> redisTemplate = new MyRedisTemplate<>(lettuceConnectionFactory);

        redisTemplateArr[db] = redisTemplate;
        return redisTemplate;
    }

}
